package com.eslserver.action.esl;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.ESLServerPageDispatcher;
import com.eslserver.core.aware.ESLAware;
import com.eslserver.dao.CoordinatorDAO;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.to.ESL;

@SuppressWarnings("serial")
public class AddESL extends HttpServlet implements ESLAware,
		ESLServerPageDispatcher {

	public static final Logger LOG = LoggerFactory.getLogger(AddESL.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			Integer eslID = Integer.valueOf(req.getParameter(PARAM_ESL_ID));

			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();
			CoordinatorDAO coordinatorDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY)
					.getCoordinatorDAO();

			ESL esl = null;
			Date now = new Date();
			if (eslID.equals(0)) {
				esl = ESL.createESL();
				esl.setCreateDate(now);
				esl.setDelete(false);
			} else {
				esl = eslDAO.loadESL(eslID);
			}

			if (req.getParameter(PARAM_ESL_NAME) != null
					&& req.getParameter(PARAM_ESL_NAME).length() > 0) {
				esl.setName(req.getParameter(PARAM_ESL_NAME));
			}
			if (req.getParameter(PARAM_ESL_MAC) != null
					&& req.getParameter(PARAM_ESL_MAC).length() > 0) {
				esl.setMacAddress(req.getParameter(PARAM_ESL_MAC));
			}
			if (req.getParameter(PARAM_COOR_NAME) != null
					&& req.getParameter(PARAM_COOR_NAME).length() > 0) {
				esl.setCoordinator(coordinatorDAO.loadCoordinatorByID(Integer
						.valueOf(req.getParameter(PARAM_COOR_NAME))));
			}
			if (req.getParameter(PARAM_ESL_DESCRIPTION) != null) {
				esl.setDescription(req.getParameter(PARAM_ESL_DESCRIPTION));
			}

			esl.setModifyDate(now);

			if (eslID.equals(0)) {
				eslDAO.addESL(esl);
				eslID = esl.getESLID();
			} else {
				eslDAO.updateESL(esl);
			}

			req.setAttribute(ATTRIBUTE_ESL_ID, eslID);

			RequestDispatcher dispatcher = req.getRequestDispatcher(ESL_INFO);
			dispatcher.forward(req, resp);
		} catch (DAOException e) {
			LOG.error("Error adding ESL.", e);
		}

	}

}
